package com.youtills.core.random;

/**
 * Created by IntelliJ IDEA.
 * User: ravi
 * Date: 8/12/12
 * Time: 2:01 PM
 * To change this template use File | Settings | File Templates.
 */
public class RandomString {
    /**
     * Default Minimum length for RandomString.
     */
    public static final int MIN_LENGTH = 10;

    /**
     * The random number generator.
     */
    private static java.util.Random r = new java.util.Random();

    /* Set of characters that is valid. Must be printable, memorable,
     * and "won't break HTML" (i.e., not '<', '>', '&', '=', ...).
     * or break shell commands (i.e., not '<', '>', '$', '!', ...).
     * I, L and O are good to leave out, as are numeric zero and one.
     */
    public static final char[] ALLOWED_CHARS = {
        // Comment out next two lines to make upper-case-only, then
        // use String toUpper() on the user's input before validating.
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n',
        'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        '2', '3', '4', '5', '6', '7', '8', '9',
        '!', '@', '$', '*'
    };


    private int length;
    private final char[] allowedChars;

    private static RandomString instance = new RandomString(MIN_LENGTH, ALLOWED_CHARS);

    public RandomString(int length, char[] allowedChars) {
        this.length = length;
        this.allowedChars = allowedChars;
    }

    public static RandomString getInstance() {
        return instance;
    }

    /* Generate a Password object with a random password. */
    public String getNext() {
        return getNext(length);
    }

    /* Generate a String object with a random password. */
    public String getNext(int length) {
        if (length < 1) {
            throw new IllegalArgumentException(
                    "Length must be at least 1, invalid length=" + length);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(allowedChars[r.nextInt(allowedChars.length)]);
        }
        return sb.toString();
    }

    public int getLength(){
        return length;
    }

    public char[] getAllowedChars(){
        return allowedChars;
    }
}